<?php

namespace Erp\C\Orders;
use Think;
use Erp\C\Orders\ShippingDeclare;
use Erp\C\Orders\Tn\Shipping;
use Erp\C\Api\Shopee\ShopeeService;
use Fn;
/**
 * 预导入订单 数据转换器
 *
 */
class OrdersLabel {

    private $_debug = false;
    private $_versions = 1;
    private $_ordersInfo = array();
    // 目前有的doc模板
            //"DG_TN",
            //"BJYW_TN",
            //"YWSH_TN",
            //"SGPOST_TN",
            //"SEPOST_TN",
            //"SEPOST",
            //"MYPOSTREG",
            //"HZ_TN",
            //"MYPOST",
            //"JYRUISHI_TN",
            //"WPT_TN",
            //"UNI",
            //"UNIAU"
    private $_docModel = array(
            //"DGPT",
            "SG",
            "HZ",
            "JYRUISHI",
            "RUZX",
            "RUZX_TN",
            "WPT",
			'FJWISH'
        );

    function __construct($debug=false){
        $this->_debug = $debug? true: false;
    }

    function setParams($params){
        $this->_ordersInfo = $params;
        return $this;
    }

	/**
     * @param $ordersIdArr array(0=>orders_id,1=>orders_id)
     * @return array('success'=>array(),error=>)
     */
    
    function getLabelByOid($ordersIdArr)
    {
        $res = $this->getLabelInfo($ordersIdArr);
        if(isset($res['data']) && !empty($res['data'])){
            $tmp = $this->savePdf($res["data"]);
            foreach ($tmp as $key => $value) {
                if($value) $res['success'][$key] = $value;
                else       $res['error'][$key] = $value;
            }
            unset($res['data']);
        }
        return $res;
    }

    function getLabelByOidV3($ordersIdArr){ 
        //echo 11;die;
        // $this->_versions = 2;
        $order = D('Orders');
        $res = $this->getLabelInfo($ordersIdArr);
        Fn\App::log("pdf",$res,"面单数据");
        $newRes = array();
        //print_r($res);die;
        if(isset($res['data']) && !empty($res['data'])){
            $ordersLabelpdf = array();
            foreach($res["data"] as $oId=>$ordersInfo){
                // if($oId != '1122371013')return false;
                $ordersLabelpdf[$oId] = $ordersInfo;
            }
            // print_r($ordersLabelpdf);die;
            $pdfTmp = $this->savePdf3($ordersLabelpdf);
            
            foreach ($pdfTmp as $key => $value) {
                if($value) $pdfRes['success'][$key] = $value;
                else       $pdfRes['error'][$key] = $value;
            }
            unset($pdfRes['data']);
           
            $newRes["success"] = array_merge(Fn\Arr::processKey($pdfRes["success"],"oid","+PRE"),Fn\Arr::processKey($docRes["success"],"oid","+PRE"));
            $newRes["error"] = array_merge(Fn\Arr::processKey($pdfRes["error"],"oid","+PRE"),Fn\Arr::processKey($docRes["error"],"oid","+PRE"));
            $newRes["success"] = Fn\Arr::processKey($newRes["success"],"oid","-PRE");
            $newRes["error"] = Fn\Arr::processKey($newRes["error"],"oid","-PRE");
        }
        $resFinal = array();
        $resOrders = $res;
        if(isset($resOrders['data'])){
            unset($resOrders['data']);
        }
        if(!empty($newRes)){
            if(!is_array($resOrders['success'])){
                $resOrders['success'] = array();
            }
             if(!is_array($resOrders['error'])){
                $resOrders['error'] = array();
            }
             if(!is_array($newRes['success'])){
                $newRes['success'] = array();
            }
             if(!is_array($newRes['error'])){
                $newRes['error'] = array();
            }
            $resFinal['success'] = $resOrders['success']+$newRes["success"];
            $resFinal['error'] = $resOrders['error']+$newRes["error"];
        }else{
            $resFinal = $resOrders;
        }
        return $resFinal;
    }

    //检测生成pdf版本是否适用于v3
    private function _checkGetLabelV3($ordersId){
        $pdfV3 = \Fn\App::getPdfV3();
        if(!$pdfV3)return false;
        $res = M('orders')->where(array('orders_id'=>$ordersId))->find();
        $shippingMethod = $res['orders_shipping_method'];
        $country = $res['orders_shipping_country_iso'];
        $shippingMethodSvg = $this->_shippingMethodChange($shippingMethod,$country);
        if(in_array($shippingMethodSvg, $pdfV3)){
            return true;
        }else{
            return false;
        }
    }

    //针对特殊渠道进行处理
    private function _shippingMethodChange($shippingMethod,$country){
        $shippingMethodSvg = $shippingMethod;
        if($shippingMethod === 'DG_TN'){
            if(in_array($country, array('NO','FR','DE','PL','SK','HR','CZ','SI','AU'))){
                $shippingMethodSvg = $shippingMethod.'-EUR';
            }else if($country === 'NZ'){
                $shippingMethodSvg = $shippingMethod.'-NZ';
            }
        }elseif($shippingMethod === 'SLS') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'SLSYW') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'SLSPY') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'SLSPYYW') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'DGPT' && ($country==='DE' || $country==='US')) {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'LWCT' && $country==='CA') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'DGWISH' && $country==='US') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'SEKO' && $country==='NG') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }elseif($shippingMethod === 'YWSEKO' && $country==='NG') {
            $shippingMethodSvg = $shippingMethod.'-'.$country;
        }
        return $shippingMethodSvg;
    }

    public function checkGetLabelV3($value){
        $flag = $this->_checkGetLabelV3($value);
        return $flag;
    }

    function getLabelByOidV2($ordersIdArr)
    {	
        $arrV3 = array();
        foreach ($ordersIdArr as $key => $value) {
            // if($value != '1122801775')continue;
            $flag = $this->_checkGetLabelV3($value); 
            if($flag){
                $arrV3[] = $value;
                unset($ordersIdArr[$key]);
            }
        } 
		if($arrV3){
			$resV3 = $this->getLabelByOidV3($arrV3);
		}else{
			$resV3 = false;
		}
        $ordersIdArr = array_values($ordersIdArr);
        //echo 11;die;
        $this->_versions = 2;
        $res = $this->getLabelInfo($ordersIdArr);
		//Fn\App::log("pdf",$res,"面单数据");
        $newRes = array();
		//print_r($res);die;
    	if(isset($res['data']) && !empty($res['data'])){
            $ordersLabelpdf = array();
            $ordersLabeldoc = array();
            foreach($res["data"] as $oId=>$ordersInfo){
				
                //!in_array($ordersInfo["country_iso"],Fn\App::createPdfCountryList()) && 
                if(in_array($ordersInfo["method"],$this->_docModel)){
                    $ordersLabeldoc[$oId] = $ordersInfo;
                }else{
                    $ordersLabelpdf[$oId] = $ordersInfo;
                }
            }
			//print_r($ordersLabelpdf);die;
      		$pdfTmp = $this->savePdf($ordersLabelpdf);
			
      		foreach ($pdfTmp as $key => $value) {
      			if($value) $pdfRes['success'][$key] = $value;
      			else       $pdfRes['error'][$key] = $value;
      		}
            unset($pdfRes['data']);
            $docTmp = $this->saveDoc($ordersLabeldoc);
            foreach ($docTmp as $key => $value) {
                if($value) $docRes['success'][$key] = $value;
                else       $docRes['error'][$key] = $value;
            }
      		unset($docRes['data']);

            $newRes["success"] = array_merge(Fn\Arr::processKey($pdfRes["success"],"oid","+PRE"),Fn\Arr::processKey($docRes["success"],"oid","+PRE"));
            $newRes["error"] = array_merge(Fn\Arr::processKey($pdfRes["error"],"oid","+PRE"),Fn\Arr::processKey($docRes["error"],"oid","+PRE"));
            $newRes["success"] = Fn\Arr::processKey($newRes["success"],"oid","-PRE");
            $newRes["error"] = Fn\Arr::processKey($newRes["error"],"oid","-PRE");
  		}
        $resFinal = array();
        $resOrders = $res;
        if(isset($resOrders['data'])){
            unset($resOrders['data']);
        }
        if(!empty($newRes)){
            if(!is_array($resOrders['success'])){
                $resOrders['success'] = array();
            }
             if(!is_array($resOrders['error'])){
                $resOrders['error'] = array();
            }
             if(!is_array($newRes['success'])){
                $newRes['success'] = array();
            }
             if(!is_array($newRes['error'])){
                $newRes['error'] = array();
            }
            $resFinal['success'] = $resOrders['success']+$newRes["success"];
            $resFinal['error'] = $resOrders['error']+$newRes["error"];
        }else{
            $resFinal = $resOrders;
        }
        
        // $resV3 =array ( 'success' => array ( '1122371013' => 'Public/Data/Files/20170730/1122371013.pdf', ), 'error' => array ( ), );
        // $resFinal =array ( 'success' => array ( '1122371012' => 'Public/Data/Files/20170730/1122371012.pdf','1122371012' => 'Public/Data/Files/20170730/1122371012.pdf','1122371012' => 'Public/Data/Files/20170730/1122371012.pdf', ),  );
        // // $resFinal = array_merge($resV3,$resFinal);
        $tmpArr = array();
        if($resV3){
            if(!is_array($resFinal['success'])){
                $resFinal['success'] = array();
            }
             if(!is_array($resFinal['error'])){
                $resFinal['error'] = array();
            }
             if(!is_array($resV3['success'])){
                $resV3['success'] = array();
            }
             if(!is_array($resV3['error'])){
                $resV3['error'] = array();
            }
            $tmpArr['success'] = $resFinal['success']+$resV3['success'];
            $tmpArr['error'] = $resFinal['error']+$resV3['error'];
        }else{
            $tmpArr = $resFinal;
        }
      	return $tmpArr;
    }


    private function _labelData($ordersInfo)
    {	
        if(empty($ordersInfo)) return false;
    	$ordersId = $ordersInfo['orders_id'];
    	$ordersModel = M("orders");
        $osModel = D("OrdersShippingMethod");
    	$ordersInfo1 = M("orders_deliver_address")->where("orders_id=" . $ordersId)->find();
        $method = $printInfo["method"] = $ordersInfo["orders_shipping_method"];
        $shippingType = $osModel->getShippingTypeByCode($method);
		
       // $isErp = in_array(strtoupper($shippingType) ,array('ERP','CF','WISH','LAZADA','JUMIA','EYB'));
		$isErp = in_array(strtoupper($shippingType) ,array('ERP','CP','CF','WISH','ALIEXPRESS','LAZADA','JUMIA','EYB','SP','DQ','KTS','YYM'));
        if( $this->_debug) echo $method.'----'.$ordersId;
		
        if(!$isErp || !in_array($method,Fn\App::createPdfShippintMethod())){
			
            $errorOrders[] = $ordersId;
            $ordersModel->where("orders_id=".$ordersId)->setField("orders_pdf_exist",1);
            if( $this->_debug) echo "---跳出<br>\n";
            return false;
        }
		
        if( $this->_debug) echo "---处理数据<br>\n";
        $correctOrders[] = $labelFile;
		
        // 设置打印背景
            if ($method == "BJYW_TN") {
                $printInfo["backgroundImg"] = array("BJYW_TN1.png", "BJYW_TN2.png");
            } else if ($method == "YWSH_TN") {
                $printInfo["backgroundImg"] = array("SHYW_TN1.png", "SHYW_TN2.png");
            } 
            //$printMethod = $method;

            if($method== "RUZX"||$method== "RUZX_TN"){
                $postCode = intval($ordersInfo1["orders_delivery_postcode"]);
                $printInfo["zone"]="B";

                if($postCode>=187000&&$postCode<=199000){
                    $printInfo["zone"] = "A";
                }
                if($method== "RUZX"){
                    if(trim($ordersInfo["orders_tn"]) === trim($ordersInfo["orders_id"])){
                        $ordersInfo["orders_tn"] = 'CF'.$ordersInfo["orders_id"];
                    }
                    if(trim($ordersInfo["orders_tn"])===''){
                        $ordersInfo["orders_tn"] = 'CF'.$ordersInfo["orders_id"];        
                    }
                }
                
            }
			if($method == 'SPTW_TN' || $method == 'SPTWDP_TN' || $method == 'SLS' || $method == 'SLSPY' || $method == 'SPTWYW_TN' || $method == 'SPTWDPYW_TN' || $method == 'SLSYW' || $method == 'SLSPYYW'){
				
				$origOrdersId = $ordersInfo['orders_original_id'];
				$origOid = explode("-",$origOrdersId);
				$oidS = $origOid[1];
				$flag = 1;
				if(empty($oidS)){
					$flag = 0;
				}else{
					$spOrdersInfo = M("sp_orders")->field("sp_shipping_method,sp_goods_to_declare,sp_cod")->where("sp_orders_id = '$oidS'")->find();
					if( $spOrdersInfo && $spOrdersInfo['sp_shipping_method'] && $spOrdersInfo['sp_goods_to_declare']!== false && $spOrdersInfo['sp_cod']!== false ){
						$printInfo = array_merge($printInfo,$spOrdersInfo);
						$orderPriceInfo = M('orders_other')->field("orders_price,orders_currency")->where("orders_id=" . $ordersId)->find();
						$printInfo = array_merge($printInfo,$orderPriceInfo);
						$printInfo['orders_original_id'] = $oidS;
					}else{
						$flag = 0;
					}
				}
				if(!$flag){
					M("orders_history")->add(
						array(
							"orders_id"=>$ordersId,
							"orders_history_create_date"=>date("Y-m-d",time()),
							"orders_history_create_time"=>time(),
							"user_id"=>\Fn\App::user(),
							"orders_history_remark"=>"SP获取本地PDF失败"
						)
					);
					return false;
				}
			}
			
            $printInfo["sendInfo"] = array( 
                $ordersInfo1["orders_delivery_name"],
                $this->replaceStr($ordersInfo1["orders_delivery_address"]),
                $this->replaceStr($ordersInfo1["orders_delivery_address2"]),
                $ordersInfo1["orders_delivery_city"],
                $this->replaceStr($ordersInfo1["orders_delivery_state"]),
                $ordersInfo1["orders_delivery_postcode"],
                $ordersInfo1["orders_delivery_tel"],
                $ordersInfo1["orders_delivery_country"]
            );
			
            $printInfo["ordersId"] = $ordersId;
            $printInfo["importDate"] = date("Ymd",$ordersInfo["orders_import_time"]);
            $printInfo["ordersDate"] = date("d-m-Y",$ordersInfo["orders_import_time"]);
            $printInfo["postCode"] = $ordersInfo1["orders_delivery_postcode"];
            $printInfo["phoneNum"] = $ordersInfo1["orders_delivery_tel"];
            $printInfo["country_iso"] = trim($ordersInfo1["orders_delivery_country_iso"]);
            $printInfo["country_iso"]=$printInfo["country_iso"]=="UK"?"GB":$printInfo["country_iso"];
            $printInfo["country"] = Fn\Country::cnName($ordersInfo1["orders_delivery_country_iso"]);
            $countryTn = Fn\CountryTn::getCountryTn($ordersInfo1["orders_delivery_country_iso"]);
            $printInfo["Fenjian"] = Fn\App::returnFenJian($printInfo["country_iso"]);
            if($printInfo["country_iso"]=="US"){
                $printInfo["codeIdent"] = Fn\App::getCodeIdentByUS($printInfo["postCode"]);
            }
			
            if($printInfo["country_iso"]=="RU"){
                $printInfo["codeIdent"] = Fn\App::getCodeIdentByRU($printInfo["postCode"]); 
            }
			
            $printInfo["partitionCode"] = Fn\App::getPartitionCode($printInfo["country_iso"],"partition_code");
            $printInfo["partitionCode_tn"] = Fn\App::getPartitionCode($printInfo["country_iso"],"g_partition_code");
            $printInfo["countryTn"] = $countryTn[0]."     ".$countryTn[1]."      ".$countryTn[2];

            $ordersProduct = M("orders_product")->where("orders_id=" . $ordersId)->select();
			
            $sd = new ShippingDeclare();
            $productInfo = $sd->getCustomsInfoByOid($ordersId);
			
            $printInfo["productInfo"]["pname"] = $productInfo["nameCn"];
            $printInfo["productInfo"]["weight"] = $productInfo["weight"]/1000;
            $printInfo["productInfo"]["realWeight"] = $productInfo["realWeight"];
            $printInfo["productInfo"]["cost"] = $productInfo["pice"];
            $printInfo["productInfo"]["pname_en"] = $productInfo["nameEn"];
		
            $psum = 0;
            foreach($ordersProduct as $val){
                $psum += $val["orders_product_quantity"];
            }
            $printInfo["productSum"] = $psum;
			//若订单为退款订单，则订单产品数量需减去退款订单的数量
			if(in_array($ordersInfo['orders_payment_status'],array(3,4))){
				$csRefundTable = M('cshelper_refund');
				$csList = $csRefundTable->field("refund_id")->where("orders_id=" . $ordersId)->select();
				if(!empty($csList)){
					$refundIdList = Fn\Arr::neaten($csList,"refund_id");
					$refundIds = implode(",",$refundIdList);
					$csRefundProdTable = M("cshelper_refund_product");
					$csRefundNumber = $csRefundProdTable->where("refund_id in ($refundIds)")->sum("refund_product_qty");
					if(!empty($csRefundNumber) && $csRefundNumber>0){
						$printInfo["productSum"] -= $csRefundNumber;
					}	
				}
			}
            $printInfo['tn'] = $ordersInfo["orders_tn"];
				
            // 合并传来的数组
            if(isset($this->_ordersInfo[$ordersId])){
                $printInfo = array_merge($printInfo,$this->_ordersInfo[$ordersId]);
            }
			//print_r($printInfo);die;
			Fn\App::log('local',$printInfo,"Lzd获取PDF成功");
            return $printInfo;

    }

    //整理订单数据
    public function neatenData($ordersInfo){
        $sd = new ShippingDeclare();
        $printInfo = array();
        $ordersId = $ordersInfo['orders_id'];
        $printInfo["method"] = $ordersInfo["orders_shipping_method"];
        $printInfo["sendInfo"] = array( 
            $ordersInfo["orders_delivery_name"],
            $this->replaceStr($ordersInfo["orders_delivery_address"]),
            $this->replaceStr($ordersInfo["orders_delivery_address2"]),
            $ordersInfo["orders_delivery_city"],
            $this->replaceStr($ordersInfo["orders_delivery_state"]),
            $ordersInfo["orders_delivery_postcode"],
            $ordersInfo["orders_delivery_tel"],
            $ordersInfo["orders_delivery_country"]
        );
        $printInfo["ordersId"] = $ordersInfo['orders_id'];
        $printInfo["importDate"] = date("Ymd",$ordersInfo["orders_import_time"]);
        $printInfo["ordersDate"] = date("d-m-Y",$ordersInfo["orders_time"]);
        $printInfo["ordersTime"] = date("Y/m/d H:i:s",$ordersInfo["orders_time"]);

        $printInfo["postCode"] = $ordersInfo["orders_delivery_postcode"];
        $printInfo["phoneNum"] = $ordersInfo["orders_delivery_tel"];
        $printInfo["country_iso"] = trim($ordersInfo["orders_delivery_country_iso"]);
        $printInfo["country_iso"]=$printInfo["country_iso"]=="UK"?"GB":$printInfo["country_iso"];
        $printInfo["country"] = Fn\Country::cnName($ordersInfo["orders_delivery_country_iso"]);
        $printInfo["country_en"] = Fn\Country::enName($ordersInfo["orders_delivery_country_iso"]);
        $countryTn = Fn\CountryTn::getCountryTn($ordersInfo["orders_delivery_country_iso"]);
        $printInfo["Fenjian"] = Fn\App::returnFenJian($printInfo["country_iso"]);
        if($printInfo["country_iso"]=="US"){
            $printInfo["codeIdent"] = Fn\App::getCodeIdentByUS($printInfo["postCode"]);
        }
        
        if($printInfo["country_iso"]=="RU"){
            $printInfo["codeIdent"] = Fn\App::getCodeIdentByRU($printInfo["postCode"]); 
        }
        
        $printInfo["partitionCode"] = Fn\App::getPartitionCode($printInfo["country_iso"],"partition_code");
        $printInfo["partitionCode_tn"] = Fn\App::getPartitionCode($printInfo["country_iso"],"g_partition_code");
        $printInfo["countryTn"] = $countryTn[0]."     ".$countryTn[1]."      ".$countryTn[2];

        $productInfo = $sd->getCustomsInfoByOid($ordersInfo['orders_id']);
         
        $printInfo["productInfo"]["pname"] = $productInfo["nameCn"];
        $printInfo["productInfo"]["weight"] = $productInfo["weight"]/1000;
        $printInfo["productInfo"]["realWeight"] = $productInfo["realWeight"];
        $printInfo["productInfo"]["cost"] = $productInfo["pice"];
        $printInfo["productInfo"]["pname_en"] = $productInfo["nameEn"];
        $psum = 0;
        $ordersProduct = $ordersInfo['orders_items'];
        foreach($ordersProduct as $val){
            $psum += $val["orders_product_quantity"];
        }
        $printInfo["productSum"] = $psum;
        if(in_array($ordersInfo['orders_payment_status'],array(3,4))){
            $csRefundTable = M('cshelper_refund');
            $csList = $csRefundTable->field("refund_id")->where("orders_id=" . $ordersId)->select();
            if(!empty($csList)){
                $refundIdList = Fn\Arr::neaten($csList,"refund_id");
                $refundIds = implode(",",$refundIdList);
                $csRefundProdTable = M("cshelper_refund_product");
                $csRefundNumber = $csRefundProdTable->where("refund_id in ($refundIds)")->sum("refund_product_qty");
                if(!empty($csRefundNumber) && $csRefundNumber>0){
                    $printInfo["productSum"] -= $csRefundNumber;
                }   
            }
        }
        $printInfo['tn'] = $ordersInfo["orders_tn"];
        $methodName = '_recreateData'.$ordersInfo["orders_shipping_method"];
        $method = method_exists($this, $methodName);
        if($method){
           $printInfo = $this->$methodName($printInfo,$ordersInfo);
        }
        $apiType = D('OrdersShippingMethod')->getShippingTypeByCode($ordersInfo["orders_shipping_method"]);
        $methodTypeName = '_recreateData'.$apiType;
        $methodType = method_exists($this, $methodTypeName);
        if($methodType){
           $printInfo = $this->$methodTypeName($printInfo,$ordersInfo);
        }
        // 合并传来的数组
        if(isset($this->_ordersInfo[$ordersId])){
            $printInfo = array_merge($printInfo,$this->_ordersInfo[$ordersId]);
        }
        return $printInfo;
    }

    //sls数据处理
    private function _recreateDataSLS($printInfo,$ordersInfo){
        $shopeeGetOrderLogistics = new ShopeeService\ShopeeGetOrderLogistics();
        $origOrdersId = $ordersInfo['orders_original_id'];
        $origOid = explode("-",$origOrdersId);
        $oidS = $origOid[1];
        $spOrdersInfo = M("sp_orders")->field("sp_shipping_method,sp_goods_to_declare,sp_cod")->where("sp_orders_pk = '$origOrdersId'")->find();

        if($spOrdersInfo && $spOrdersInfo['sp_shipping_method'] && $spOrdersInfo['sp_goods_to_declare']!== false && $spOrdersInfo['sp_cod']!== false){
            $printInfo = array_merge($printInfo,$spOrdersInfo);
            $orderPriceInfo = M('orders_other')->field("orders_price,orders_currency")->where("orders_id=" . $ordersInfo['orders_id'])->find();
            $printInfo = array_merge($printInfo,$orderPriceInfo);
            $printInfo['orders_original_id'] = $oidS;
            $response = $shopeeGetOrderLogistics->apiGetOrderLogistics($ordersInfo);
            if(!isset($response['logistics']['service_code']))return false;
            $printInfo['service_code'] = $response['logistics']['service_code']?$response['logistics']['service_code']:'';
            $printInfo['first_mile_name'] = $response['logistics']['first_mile_name']?$response['logistics']['first_mile_name']:'';
            $printInfo['last_mile_name'] = $response['logistics']['last_mile_name']?$response['logistics']['last_mile_name']:'';
            if($ordersInfo['orders_id'] === '1124818127'){
                return false;
            }
            // if(!$printInfo['service_code'])return false;
        }
        return $printInfo;
    }

    //Jumia数据处理
    private function _recreateDataJUMIA($printInfo,$ordersInfo){
        $shopeeGetOrderLogistics = new ShopeeService\ShopeeGetOrderLogistics();
        $origOrdersId = $ordersInfo['orders_original_id'];
        $origOid = explode("-",$origOrdersId);
        $oidS = $origOid[1];
        $printInfo['orders_original_id'] = $oidS;
        return $printInfo;
    }

    //slsyw数据处理
    private function _recreateDataSLSYW($printInfo,$ordersInfo){
        $shopeeGetOrderLogistics = new ShopeeService\ShopeeGetOrderLogistics();
        $origOrdersId = $ordersInfo['orders_original_id'];
        $origOid = explode("-",$origOrdersId);
        $oidS = $origOid[1];
        $spOrdersInfo = M("sp_orders")->field("sp_shipping_method,sp_goods_to_declare,sp_cod")->where("sp_orders_pk = '$origOrdersId'")->find();

        if($spOrdersInfo && $spOrdersInfo['sp_shipping_method'] && $spOrdersInfo['sp_goods_to_declare']!== false && $spOrdersInfo['sp_cod']!== false){
            $printInfo = array_merge($printInfo,$spOrdersInfo);
            $orderPriceInfo = M('orders_other')->field("orders_price,orders_currency")->where("orders_id=" . $ordersInfo['orders_id'])->find();
            $printInfo = array_merge($printInfo,$orderPriceInfo);
            $printInfo['orders_original_id'] = $oidS;
            $response = $shopeeGetOrderLogistics->apiGetOrderLogistics($ordersInfo);
            if(!isset($response['logistics']['service_code']))return false;
            $printInfo['service_code'] = $response['logistics']['service_code']?$response['logistics']['service_code']:'';
            $printInfo['first_mile_name'] = $response['logistics']['first_mile_name']?$response['logistics']['first_mile_name']:'';
            $printInfo['last_mile_name'] = $response['logistics']['last_mile_name']?$response['logistics']['last_mile_name']:'';
            if($ordersInfo['orders_id'] === '1124818127'){
                return false;
            }
            // if(!$printInfo['service_code'])return false;
        }
        return $printInfo;
    }

    //SLSPY数据处理
    private function _recreateDataSLSPY($printInfo,$ordersInfo){
        $shopeeGetOrderLogistics = new ShopeeService\ShopeeGetOrderLogistics();
        $origOrdersId = $ordersInfo['orders_original_id'];
        $origOid = explode("-",$origOrdersId);
        $oidS = $origOid[1];
        $spOrdersInfo = M("sp_orders")->field("sp_shipping_method,sp_goods_to_declare,sp_cod")->where("sp_orders_pk = '$origOrdersId'")->find();

        if($spOrdersInfo && $spOrdersInfo['sp_shipping_method'] && $spOrdersInfo['sp_goods_to_declare']!== false && $spOrdersInfo['sp_cod']!== false){
            $printInfo = array_merge($printInfo,$spOrdersInfo);
            $orderPriceInfo = M('orders_other')->field("orders_price,orders_currency")->where("orders_id=" . $ordersInfo['orders_id'])->find();
            $printInfo = array_merge($printInfo,$orderPriceInfo);
            $printInfo['orders_original_id'] = $oidS;
            $response = $shopeeGetOrderLogistics->apiGetOrderLogistics($ordersInfo);//print_r($response);die();
            if(!isset($response['logistics']['service_code']))return false;
            $printInfo['service_code'] = $response['logistics']['service_code']?$response['logistics']['service_code']:'';
            $printInfo['first_mile_name'] = $response['logistics']['first_mile_name']?$response['logistics']['first_mile_name']:'';
            $printInfo['last_mile_name'] = $response['logistics']['last_mile_name']?$response['logistics']['last_mile_name']:'';
            // if(!$printInfo['service_code'])return false;
        }
        return $printInfo;
    }

    //SLSPYYW数据处理
    private function _recreateDataSLSPYYW($printInfo,$ordersInfo){
        $shopeeGetOrderLogistics = new ShopeeService\ShopeeGetOrderLogistics();
        $origOrdersId = $ordersInfo['orders_original_id'];
        $origOid = explode("-",$origOrdersId);
        $oidS = $origOid[1];
        $spOrdersInfo = M("sp_orders")->field("sp_shipping_method,sp_goods_to_declare,sp_cod")->where("sp_orders_pk = '$origOrdersId'")->find();

        if($spOrdersInfo && $spOrdersInfo['sp_shipping_method'] && $spOrdersInfo['sp_goods_to_declare']!== false && $spOrdersInfo['sp_cod']!== false){
            $printInfo = array_merge($printInfo,$spOrdersInfo);
            $orderPriceInfo = M('orders_other')->field("orders_price,orders_currency")->where("orders_id=" . $ordersInfo['orders_id'])->find();
            $printInfo = array_merge($printInfo,$orderPriceInfo);
            $printInfo['orders_original_id'] = $oidS;
            $response = $shopeeGetOrderLogistics->apiGetOrderLogistics($ordersInfo);//print_r($response);die();
            if(!isset($response['logistics']['service_code']))return false;
            $printInfo['service_code'] = $response['logistics']['service_code']?$response['logistics']['service_code']:'';
            $printInfo['first_mile_name'] = $response['logistics']['first_mile_name']?$response['logistics']['first_mile_name']:'';
            $printInfo['last_mile_name'] = $response['logistics']['last_mile_name']?$response['logistics']['last_mile_name']:'';
            // if(!$printInfo['service_code'])return false;
        }
        return $printInfo;
    }

    //东莞中邮挂号 普通国家
    private function _recreateDataDG_TN($printInfo,$ordersInfo){
        $shippingMethodSvg = $this->_shippingMethodChange($printInfo['method'],$printInfo['country_iso']);
        if($shippingMethodSvg === 'DG_TN'){
            $printInfo = $this->setPrintInfo($printInfo);
        }
        return $printInfo;
    }

    //东莞中邮平邮 普通国家
    private function _recreateDataDGPT($printInfo,$ordersInfo){
        $shippingMethodSvg = $this->_shippingMethodChange($printInfo['method'],$printInfo['country_iso']);
        $printInfo = $this->setPrintInfo($printInfo);
        if($shippingMethodSvg === 'DGPT' || $shippingMethodSvg === 'DGPT-DE' || $shippingMethodSvg === 'DGPT-US'){
            if (!empty($printInfo['tn'])) {
                if(is_numeric($printInfo['tn'][0]) && $printInfo['tn'][0] != '0'){
                    $printInfo['flagTn'] = '0'.$printInfo['tn'];
                }else{
                    $printInfo['flagTn'] = $printInfo['tn'];
                }   
            }
        }
        return $printInfo;
    }

    // 过滤字符串
    private function replaceStr($str,$array = array("<"=>"&lt;",">"=>"&gt;","="=>"=3D") ){
        return strtr($str,$array);
    }
    
    // 判断 如果该运输方式是从API获取的面单信息 就要判断传过来API获取的数据没有
    public function fileterOrdersLabelApi($method){
		//
        // 如果没有传来了API面单数据
        if(empty($this->_ordersInfo)){
			
            $t = array('wish','eyb','lazada','jumia');
            $apiType = D('OrdersShippingMethod')->getShippingTypeByCode($method);
            if(in_array(strtolower($apiType), $t)){
            	return false;
            }
        }
        return true;
    }
    /*
     *   "address_cn": "东莞市黄江镇黄牛埔村村委会华南塑胶城B区97-98号二楼",
            "name_cn": "赵红",
            "address_en": "Second floor,No.97-98 District B,Huanan Plastic City,Huang Niu Pu Village, Huangjiang Town, Dongguan",
            "name_en": "Zhao Hong"
     * 
     * */
    // 改变面单信息的方法
    private function setPrintInfo($printInfo){
        // 这里是当 运输方式为 东莞中邮小包 的且发送国家是英国的
        if($printInfo['method'] == 'DGPT' || $printInfo['method'] == 'DG_TN'){
            if($printInfo['country_iso'] == 'UK' || $printInfo['country_iso'] == 'GB'){
                // 因为这里的英国国家有两个iso 所以这里只用一个
                $coutry_iso = 'UK';
                $shipping_method = 'DG';     // DGPT 和 DG_TN 的统称
                
                $map = array(
                	'update_date'=>date('Y-m-d'),
                    'orders_shipping_iso'=>$coutry_iso,
                    'orders_shipping_method'=>$shipping_method,
                    'orders_shipping_count'=>array('EGT', 210)
                );
                $notShippingAddress = M('OrdersShippingAddress')->field('orders_shipping_index')->where($map)->select();
                $notShiipingIndex = array();
                foreach ($notShippingAddress as $value){
                    $notShiipingIndex[] = $value['orders_shipping_index'];
                }
                
                $ordersShingMap = array(
                	'shipping_method_code'=>$printInfo['method']
                );
                $ordersShippingInfoRes = M('OrdersShippingMethod')->field('orders_shipping_info')->where($ordersShingMap)->find();
                $ordersShippingInfo = json_decode($ordersShippingInfoRes['orders_shipping_info'], true);
                $ordersShippingFrom = $ordersShippingInfo['shipping_from'];
                
                foreach ($ordersShippingFrom as $key=>$value){
                    if(in_array($key, $notShiipingIndex)){
                        unset($ordersShippingFrom[$key]);
                    }
                }
                
                foreach ($ordersShippingFrom as $key=>$value){
                    // 这里所有的运输地址都是合法的 取出第一个
                    $printInfo['formInfo'] = $value;
                    
                    // 使用次数加1
                    $map = array(
                    	'update_date'=>date('Y-m-d'),
                        'orders_shipping_index'=>$key,
                        'orders_shipping_iso'=>$coutry_iso,
                        'orders_shipping_method'=>$shipping_method,
                    );
                    
                    $address_id = 0;
                    $ordersShippingAddresRes = M('OrdersShippingAddress')->field('address_id')->where($map)->find();
                    if(empty($ordersShippingAddresRes)){
                        $map['orders_shipping_count'] = 1;
                        $address_id = M('OrdersShippingAddress')->add($map);
                    }else{
                        $temp_map = array('address_id'=>$ordersShippingAddresRes['address_id']);
                        M('OrdersShippingAddress')->where($temp_map)->setInc('orders_shipping_count', 1);
                        $address_id = $ordersShippingAddresRes['address_id'];
                    }
                    
                    // 做记录
                    $ordersShippingAddressLog = array(
                    	'orders_id'=>$printInfo['ordersId'],
                        'address_id'=>$address_id    
                    );
                    M('ordersShippingAddressLog')->add($ordersShippingAddressLog);
                    
                    // 因为这里是循环的 只取第一个 要停止
                    break;
                }
                
                /* $printInfo['formInfo'] = array(
                        'address_cn'=>'东莞市黄江镇黄牛埔村村委会华南塑胶城B区97-98号二楼',
                        'name_cn'=>'赵红',
                        'address_en'=>'Second floor,No.97-98 District B,Huanan Plastic City,Huang Niu Pu Village, Huangjiang Town, Dongguan',
                        'name_en'=>'Zhao Hong',
                ); */
            }else{
                $printInfo['formInfo'] = array(
                        'address_en'=>'tiane road,Qiaotou,Dongguan.',
                );
            }
        }
        return $printInfo;
    }

    //根据运输方式生成svg数据
    public function setSvgByShipping($printInfo,$pMethod = false){
        $shippingMethodSvg = '';
        if($pMethod !== false){
            $shippingMethodSvg = $pMethod;
        }else{
            $shippingMethodSvg = $this->_shippingMethodChange($printInfo['method'],$printInfo['country_iso']);
        }    
        $path = PROJECT_PUBLIC_PATH.'Data/Svg/'.$shippingMethodSvg.'.svg';
        $arr = array();
        $arr['VAR_BARCODE'] = $printInfo['tn'];
        $arr['VAR_BARCODEORGID'] = $printInfo['orders_original_id'];
        $arr['VAR_BARCODEOID'] = $printInfo['ordersId'];
        $arr['VAR_BARCODEAGENT'] = $printInfo['agentTn'];//顺丰国际代理tn
        $arr['VAR_BARCODEMAILNO'] = $printInfo['mailno'];//顺丰国际tn
        $barcodeUrlArr = $this->getBarcodeUrl($arr);
        $content = file_get_contents($path);
        if(!$content){
            $tmpContent = '';
            for ($i=1;; $i++) { 
                $content = ''; 
                $tmpShippingMethodSvg = $shippingMethodSvg.'__'.$i;
                $path = PROJECT_PUBLIC_PATH.'Data/Svg/'.$tmpShippingMethodSvg.'.svg';
                $content = file_get_contents($path);
                if(!$content){
                    break;
                }
                $tmpContent .= $this->replaceImg($content,$barcodeUrlArr,$i);
            }
        }else{
            $tmpContent = $this->replaceImg($content,$barcodeUrlArr);
            // $content = explode("<image ", $content);
            // foreach ($content as $key => $value) {
            //     if(strpos($value, 'VAR_BARCODE') !== false){
            //         $tmpV = '<image '.$value;
            //         $replaceValue
            //         $content[$key] = $replaceValue;
            //     }
            // }
            // $content = implode('<image ', $content);
            // $content = '<div class="paging p1">'.$content.'</div>';
        }
        return $tmpContent;
    }

    //获取条码url数组
    public function getBarcodeUrl($data){
        if(!is_array($data)){
            $data = array('VAR_BARCODE'=>$data);
        }
        $barcodeArr = array();
        foreach ($data as $key => $value) {
            $barcodeParam = '';
            $barcodeParam = urlencode("filetype=PNG&dpi=72&scale=1&rotation=0&font_family=Arial.ttf&font_size=0&text=".$value."&thickness=44&checksum=&code=BCGcode128");
            $barcodeUrl = \Fn\App::httpPath("/Codebar/html/image.php?ALL_ARGS=".$barcodeParam);
            // $barcodeUrl = "http://106.14.60.155/erp/Codebar/html/image.php?ALL_ARGS=".$barcodeParam;
            $barcodeArr[$key] = $barcodeUrl;
        }
        return $barcodeArr;
    }

    //替换组装svg
    public function replaceImg($content,$_barcodeUrl,$i = 1){
        $content = explode("<image ", $content);
        foreach ($content as $key => $value) {
            if(strpos($value, 'VAR_BARCODE') !== false){
                $tmpV = '<image '.$value;
                preg_match('/<image\s+.*?customname=["\'](VAR_BARCODE\w*)["\'].*?\/>/',$tmpV, $matchRes);
                if(is_array($matchRes) && !empty($matchRes[1])){
                    $tmp = $matchRes[1];
                    $barcodeUrl = $_barcodeUrl[$tmp];
                    $barcodeTag = preg_replace('/(xlink:href=")(data:.*?)"/','$1'.$barcodeUrl.'"' , $matchRes[0]);
                    $tmpContent = str_replace($matchRes[0], $barcodeTag, $tmpV);   
                    $content[$key] = str_replace('<image ', '', $tmpContent);
                }
            }
        }
        // $content = ;
        return '<div class="paging p'.$i.'">'.implode('<image ', $content).'</div>';
    }

    //生成对应面单的svg内容 
    public function getSvg($ordersId,$pMethod = false){ 
        $ordersModel = D('Orders');
        // $ordersInfo = $ordersModel->where(array('orders_id'=>intval($ordersIdArr)))->find();
        $ordersInfo = $ordersModel->combinOrderInfo($ordersId); //获取订单信息
        $res = $this->neatenData($ordersInfo);
        if(!$res['tn'])return false;
        // $res = $this->_labelData($ordersInfo);
        return $this->creaHtml($res);
    }

    //生成html  
    public function creaHtml($printInfo,$pMethod = false){
        if($printInfo){
            $arr = array();
            $itemName = $printInfo["productInfo"]["pname_en"].' * '.$printInfo['productSum'];
            $cpItemName = $printInfo["productInfo"]["pname"].$printInfo["productInfo"]["pname_en"];//中邮的产品名称 汉语加英文
            $arr['VAR_TN'] = $printInfo['tn'];
            $arr['VAR_NAME'] = $printInfo['sendInfo'][0];
            $arr['VAR_ADDRESS'] = $printInfo['sendInfo'][1];
            $arr['VAR_ADDRESS2'] = $printInfo['sendInfo'][2];
            $arr['VAR_COUNTRYNAME'] = $printInfo['country'];
            $arr['VAR_COUNTRYENNAME'] = $printInfo['country_en'];
            $arr['VAR_ITEMQTY'] = $printInfo['productSum'];
            $arr['VAR_ZIP'] = $printInfo['sendInfo'][5];
            $arr['VAR_TEL'] = $printInfo['sendInfo'][6];
            $arr['VAR_CITY'] = $printInfo['sendInfo'][3];
            $arr['VAR_STATE'] = $printInfo['sendInfo'][4];
            $arr['VAR_ORDERSDATE'] = $printInfo['ordersDate'];
            $arr['VAR_ORDERSTIME'] = $printInfo['ordersTime'];
            $arr['VAR_COUNTRYCODE'] = $printInfo['country_iso'];
            $arr['VAR_ITEMNAME'] = $itemName;
            $arr['VAR_ITEMENNAME'] = $printInfo["productInfo"]["pname_en"];
            $arr['VAR_CPITEMNAME'] = $cpItemName;
            $arr['VAR_ITEMENNAME'] = $printInfo["productInfo"]["pname_en"];
            $arr['VAR_WEIGHT'] = $printInfo['productInfo']['realWeight'];//发货重量
            $arr['VAR_DEALWEIGHT'] = $printInfo['productInfo']['weight'];//处理过的重量
            $arr['VAR_TOTALWEIGHT'] = $printInfo['productInfo']['realWeight'];
            $arr['VAR_DEALTOTALWEIGHT'] = $printInfo['productInfo']['weight'];
            $arr['VAR_PRICE'] = $printInfo['productInfo']['cost'];//处理过的价格
            $arr['VAR_TOTALPRICE'] = $printInfo['productInfo']['cost'];
            $arr['VAR_ORDERSID'] = $printInfo['ordersId'];
            $arr['VAR_ORGID'] = $printInfo['orders_original_id'];
            $arr['VAR_FLAG1'] = $printInfo['sp_goods_to_declare']?'T':'P';
            $arr['VAR_FLAGTN'] = $printInfo['flagTn'];
            $arr['VAR_FROMADDRESS'] = $printInfo['formInfo']['address_en'];
            $arr['VAR_SGCODE'] = $printInfo['SGCodeByIso'];
            $arr['VAR_PARTITIONCODE'] = $printInfo['partitionCode'];
            $arr['VAR_CODEIDENT'] = $printInfo['codeIdent'];
            $arr["VAR_FENJIAN"] = $printInfo["Fenjian"];//国家分拣码
            $arr['VAR_ITEMENALLNAME'] = $printInfo["productInfo"]["pname"].$printInfo["productInfo"]["pname_en"].' * '.$printInfo['productSum'];
            $arr['VAR_DIRECTIONCODE'] = $printInfo['directionCode'];//顺丰国际分拣码
            $arr['VAR_AGENTTN'] = $printInfo['agentTn'];//顺丰国际代理tn
            $arr['VAR_MAILNO'] = $printInfo['mailno'];//顺丰国际tn
            $arr['VAR_ISBAT'] = $printInfo['isBat'];
            $arr['VAR_SERVICECODE'] = $printInfo['service_code'];
            $arr['VAR_FIRSTMILENAME'] = $printInfo['first_mile_name'];
            $arr['VAR_LASTMILENAME'] = $printInfo['last_mile_name'];
            $arr['VAR_AREACODE'] = $printInfo['areaCode'];
            $arr['VAR_SKUS'] = $printInfo['skus'];
            $arr['VAR_STR'] = '&nbsp;';//重复空格占位变量
            $res = $this->setSvgByShipping($printInfo,$pMethod);
            $data = json_encode($arr);
            $path = PROJECT_PUBLIC_PATH.'Data/Svg/initSvg.html';
            $html = file_get_contents($path);
            $str = str_replace('<div>mysvg+++<div/>',$res,$html);
            $str = str_replace("'svgData+++'", $data, $str);
        }else{
            $str = '';
        }
        return $str;
    } 

    private function savePdf($printInfoArr)
    {	
        $tttt = microtime(true);
        Vendor('tcpdf.examples.OrderSum');

        $ordersModel=M("orders");
		//print_r($printInfoArr);die;
        $i = 0;
		$res = array();
        foreach($printInfoArr as $key=>$printInfo){
            
            // 可以改变面单信息的方法
            $printInfo = $this->setPrintInfo($printInfo);
			
			// print_r($printInfo);die;
            if($this->fileterOrdersLabelApi($printInfo['method'])){
				//print_r(11);die;

                $dir = "Public/Data/Files/".$printInfo["importDate"];
                $pdfFilePath = $dir."/".$printInfo["ordersId"].".pdf";
				$docFilePath = $dir."/".$printInfo["ordersId"].".doc";
                if(file_exists($pdfFilePath) ||  file_exists($docFilePath)){
                    unlink($pdfFilePath);
					unlink($docFilePath);
                    //continue;
                }
                $pMethod = $printInfo['method'];
				//echo $pMethod;die;
                $pdf = new \PPPPPPP();
				//print_r($pMethod);die;
                $pdf->$pMethod($printInfo);
                if (!file_exists($dir)){
                    mkdir($dir,0777,true);
                    chmod($dir,0777);
                }
                $pdf->_savePdf($dir."/".$printInfo["ordersId"]);
                // $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",1);
                unset($pdf);
                $i++;
                if(file_exists($pdfFilePath)){
                    $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",1);
                    $ordersModel->where(array("orders_id"=>$printInfo["ordersId"],'orders_status'=>300))->setField("orders_status_children",99);
                    $res[$key]=$pdfFilePath;
                    Fn\App::log('Lzd',array($key,$pdfFilePath,filesize($pdfFilePath)),"Lzd获取PDF成功");
                }
            }else{
                $res[$key] = false;
            }
        }
		
		Fn\App::log("printOrd",(microtime(true)-$tttt).'_ss');
		return $res;
    }

    private function savePdf3($printInfoArr){  
        $tttt = microtime(true);
        $ordersModel=M("orders");
        $modelHistory=M("OrdersHistory");
        //print_r($printInfoArr);die;
        $i = 0;
        $res = array();
        foreach($printInfoArr as $key=>$printInfo){
            
            // 可以改变面单信息的方法
            $printInfo = $this->setPrintInfo($printInfo);
            
            if($this->fileterOrdersLabelApi($printInfo['method'])){
                //print_r(11);die;
                $dir = "Public/Data/Files/".$printInfo["importDate"];

                $pdfFilePath = $dir."/".$printInfo["ordersId"].".pdf";
                if(file_exists($pdfFilePath)){
                    unlink($pdfFilePath);
                }
                if (!file_exists($dir)){
                    mkdir($dir,0777,true);
                    chmod($dir,0777);
                }
                $pMethod = $printInfo['method'];
                $url = \Fn\App::httpPath('/index.php?s=Erp-Orders-xpublic&cmd=GetSvgLabel&ordersId='.$printInfo["ordersId"]);
                // $url = 'http://106.14.60.155/erp/index.php?s=Erp-Orders-xpublic&cmd=GetSvgLabel&ordersId='.$printInfo["ordersId"];
                
                Fn\System::renderPdfByApi($url,$pdfFilePath);
                $i++;
                $size = filesize($pdfFilePath)/1024;
                if(file_exists($pdfFilePath) && $size>9){
                    $res[$key]=$pdfFilePath;
                    Fn\App::log('svgttt',array($url,$key,$pdfFilePath,filesize($pdfFilePath)),"获取PDF成功");
                    $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",1);
                    $ordersModel->where(array("orders_id"=>$printInfo["ordersId"],'orders_status'=>300))->setField("orders_status_children",99);
                    $modelHistory->add(array(
                        'orders_id'=>$printInfo['ordersId'],   
                        'orders_history_create_date'=>date("Y-m-d H:i:s",time()),
                        'orders_history_create_time'=>time(),
                        'user_id'=>Fn\App::userId(),
                        'orders_history_remark'=>'生成本地PDF成功'                
                    ));
                }else{
                    sleep(1);
                    @unlink($pdfFilePath);
                    Fn\System::renderPdfByApi($url,$pdfFilePath);
                    $size = filesize($pdfFilePath)/1024;
                    if(file_exists($pdfFilePath) && $size>9){
                        $res[$key]=$pdfFilePath;
                        Fn\App::log('svgttt',array($url,$key,$pdfFilePath,filesize($pdfFilePath)),"获取PDF成功");
                        $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",1);
                        $ordersModel->where(array("orders_id"=>$printInfo["ordersId"],'orders_status'=>300))->setField("orders_status_children",99);
                        $modelHistory->add(array(
                            'orders_id'=>$printInfo['ordersId'],   
                            'orders_history_create_date'=>date("Y-m-d H:i:s",time()),
                            'orders_history_create_time'=>time(),
                            'user_id'=>Fn\App::userId(),
                            'orders_history_remark'=>'生成本地PDF成功'                
                        ));
                    }else{
                        $modelHistory->add(array(
                            'orders_id'=>$printInfo['ordersId'],   
                            'orders_history_create_date'=>date("Y-m-d H:i:s",time()),
                            'orders_history_create_time'=>time(),
                            'user_id'=>Fn\App::userId(),
                            'orders_history_remark'=>'生成本地PDF失败'                
                        ));
                        @unlink($pdfFilePath);
                        $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",0);
                        $ordersModel->where(array("orders_id"=>$printInfo["ordersId"],'orders_status'=>300))->setField("orders_status_children",8);
                    }
                }
            }else{
                $res[$key] = false;
            }
        }
        
        Fn\App::log("printOrd3",(microtime(true)-$tttt).'_ss');
        return $res;
    }    
    
    // 捷优瑞士小包平邮 要获取分区码
    public function getJYRUISHICodeByIso($con_iso){
        $codeArr =  array(
                'S'=>array('NL','CZ','EE','SK','SI','SE','HU','FR','DE','DK','BE','FI','ES','PL'),
                'D'=>array('IT','NO','PF','TV','PG','VU','SB','TO','CK','FJ','KI','NC'),
                'B'=>array('AT','BG','CA','CY','MT','NZ','PT',),
                'C'=>array('AU','RU','AR','BO','BR','CL','CO','EC','GY','SR','UY','VE','GF','福克兰群岛','PY','PE','BZ','CR','SV','GT','HN','NI','PA','CU','HT','DM','DO','PR','JM','TT','MQ','BS','BB','LC','库拉索岛','AW','GD','VG','AG','KN','圣马丁','特克斯和凯科斯群岛','英属维尔京群岛','AI','圣巴泰勒米岛','蒙特塞拉特瓜德罗普岛','VI','多米尼克','KY','DZ','AO','BJ','BW','BF','BI','CM','CV','GQ','ER','ET','CI','MR','CG','RW','南苏丹','CF','TD','KM','CD','DJ','EG','立特里亚','ET','GA','GM','GH','GN','GW','KE','LS','LR','LY','MG','MW','ML','MU','MA','MZ','NA','NE','NG','ST','SN','SC','SL','SO','ZA','SD','SZ','TZ','TG','TN','UG','ZM','SO','EH','ZW','IR','IQ','SA','AF','YE','SY','AE','JO','LB','OM','KW','QA','BH','PS',)
        );
        
        foreach ($codeArr as $key=>$value) {
            if(in_array($con_iso, $value)){
                return $key;
            }
        }
        // 上面的国家都没有就返回A
        return 'A';
    }


    private function saveDoc($printInfoArr){
        $tttt = microtime(true);
        $ordersModel=M("orders");

        $i = 0;
        $res = array();
        foreach($printInfoArr as $key=>$printInfo){
            
            // 可以改变面单信息的方法
            $printInfo = $this->setPrintInfo($printInfo);
            if($this->fileterOrdersLabelApi($printInfo['method'])){
                if($printInfo['method'] == 'JYRUISHI'){
                    $printInfo['country_partition_code'] = $this->getJYRUISHICodeByIso($printInfo['country_iso']);
                }
                
                $dir = "Public/Data/Files/".$printInfo["importDate"];
                $docFilePath = $dir."/".$printInfo["ordersId"].".doc";
				$pdfFilePath = $dir."/".$printInfo["ordersId"].".pdf";
                if(file_exists($docFilePath) || file_exists($pdfFilePath)){
                    unlink($docFilePath);
					unlink($pdfFilePath);
                    //continue;
                }
                if (!file_exists($dir)){
                    mkdir($dir,0777,true);
                    chmod($dir,0777);
                }
                A('PrintOrder')->printOrdersHtml($printInfo,$docFilePath);
                $ordersModel->where("orders_id=".$printInfo["ordersId"])->setField("orders_pdf_exist",1);
                $i++;
                $res[$key]=$docFilePath;
            }else{
                $res[$key] = false;
            }            
        }
        Fn\App::log("printOrd",(microtime(true)-$tttt).'_ss');
        return $res;
    }

    private function getLabelInfo($ordersIdArr) 
    {   
        $ali = new Shipping\Aliexpress();
        $isAliyunLabel = $ali->getIsAliyunLabel();
        if(!is_array($ordersIdArr)){
            $ordersIdArr = array($ordersIdArr);
        }
        $ordersModel = M("Orders");
		
        $res = array();
        foreach($ordersIdArr as $ordersId){
            $ordersInfo =$ordersModel->where(array('orders_id'=>intval($ordersId)))->find();
            $labelPdfFile  = "Public/Data/Files/".date("Ymd",$ordersInfo["orders_import_time"])."/".$ordersId.".pdf";
            $labelDocFile  = "Public/Data/Files/".date("Ymd",$ordersInfo["orders_import_time"])."/".$ordersId.".doc";
            $labelJsonFile  = "Public/Data/Files/".date("Ymd",$ordersInfo["orders_import_time"])."/".$ordersId.".json";
			// print_r($ordersInfo);die();
            $reCreate = 1;
            // $shipType = M('orders_shipping_method')->where(array('shipping_method_code'=>$ordersInfo["orders_shipping_method"]))->getField('shipping_method_type');
            $tmpShip = D("OrdersShippingMethod")->getShippingTypeByCode($ordersInfo["orders_shipping_method"]);

            // 因为改变运输方式需重新生成面单
            if(in_array($ordersInfo["orders_shipping_method"], array('ALIRU','ALIWY_TN','SYXB','ALIJYPYYW','ALIWYYW_TN'))){
                $isAliyunLabel = true;
            }else{
                $isAliyunLabel = false;
            }
            if($ordersId == '1126344287')$isAliyunLabel = true;
            if(in_array($ordersInfo["orders_shipping_method"],$this->_docModel)){
                if($ordersInfo['orders_pdf_exist']&&file_exists($labelDocFile)){
                    $res['success'][$ordersId] = $labelDocFile;
                    $reCreate = 0;
                }
            }elseif ($shipType == 'ALIEXPRESS' && $isAliyunLabel) {
                if($ordersInfo['orders_pdf_exist']&&file_exists($labelJsonFile)){
                    $res['success'][$ordersId] = $labelJsonFile;
                    $reCreate = 0;
                }
                if($ordersInfo['orders_pdf_exist']&&file_exists($labelPdfFile)&&$ordersId!='1126344287'){
                    $res['success'][$ordersId] = $labelPdfFile;
                    $reCreate = 0;
                }
            }else{
                if($ordersInfo['orders_pdf_exist']&&file_exists($labelPdfFile)){
                    $res['success'][$ordersId] = $labelPdfFile;
                    $reCreate = 0;
                }
            }
			//echo 1;die;
            if($reCreate){
                $data = $this->_labelData($ordersInfo);
				//print_r($data);die;
                if($data===false){
                    $res['error'][$ordersId] = $ordersId;
                }else{
                    $res['data'][$ordersId] = $data;
                }
				
                //$res['success'][$ordersId] = $labelFile;
                //reMakeLabel()
            }

            
        }

        return $res;
    }


    function resetPdfStatus($ordersIdArr){
        if(!is_array($ordersIdArr)){
            $ordersIdArr = array($ordersIdArr);
        }
        $ordersModel = M("orders");
        foreach($ordersIdArr as $ordersId){
            $ordersModel->where("orders_id=".$ordersId)->setField("orders_pdf_exist",0);
        }
		// print_r($ordersIdArr);die;
        $res = $this->getLabelByOidV2($ordersIdArr);
        return $res;
    }

    //新加坡邮政挂号
    private function _recreateDataSGPOST_TN($printInfo,$ordersInfo){
        $code = $this->getSGCodeByIso($printInfo['country_iso'],$printInfo['method']);
        $printInfo['SGCodeByIso'] = "【".$code."】";
        return $printInfo;
    }

    //老挝平邮纯电池 
    private function _recreateDataLWCT($printInfo,$ordersInfo){
        $codeIdent = '';
        //分区码
        $partitionCode = $this->getPartitionCode($printInfo['country_iso'],'partition_code');
        $methodName = 'getCodeIdentBy'.$printInfo['country_iso'];
        $method = method_exists($this, $methodName);
        if($method){
            $codeIdent = $this->$methodName($printInfo['sendInfo'][5]);
        }
        $printInfo['partitionCode'] = $partitionCode;
        $printInfo['codeIdent'] = $codeIdent;

        //调用下顺丰国际物流的判断含电产品的方法
        $kts = new Shipping\Kts();
        $dTmp = array('cell_embeded','cell_in','buttoncell','special01');//含电产品
        $productList = $ordersInfo['orders_items'];

        $isBat = $kts->checkProductBatterry($productList,$dTmp);//0含电---D,1不含电---P
        if($isBat === 0){
            $printInfo['isBat'] = 'D';
        }elseif($isBat === 1){
            $printInfo['isBat'] = '';
        }else{
            return false;
        }
        return $printInfo;
    }

    // 新加坡邮政小包平邮  和  新加坡邮政小包挂号  销售分区
    /*
     $con_iso:  国家编码
    $partition: 判断是挂号还是平邮
    return:    销售分区
    */
    function getSGCodeByIso($con_iso,$partition){
        /*
         SG=新加坡邮政小包平邮
         SGPOST_TN=新加坡邮政小包挂号
        */
        //下面是分区规则
        $codeArr =  array(
                'A'=>array('MY','BN','HK','ID','PH','TW','TH','SG','JP','US','NZ','AU','IT','AT','CH','DE','ES','FR','UK','SE'),
                'B'=>array('AS','BD','BT','KH','CK','FJ','PF','GU','IN','KI','KD','KR','LO','MO','MV','MH','MF','MN','MM','NR','NP','NC','NU','MP','PK','PW','PG','WS','SB','LK','TL','TO','TV','VU','VN','CA','GR','NL'),
                'C'=>array('AL','AM','AZ','BY','BE','BA','BG','HR','CY','CZ','DK','EE','FI','GE','GI','GL','HU','IS','IE','KZ','科索沃','KG','LV','LI','LT','LU','MK','MT','MD','MC','ME','NO','PL','PT','RO','SM','RS','SK','SI','TJ','TR','TM','UZ','梵蒂冈城'),
                'D'=>array('AF','DZ','AO','AI','AG','AR','AW','BS','BH','BB','BZ','BJ','BM','BO','BW','BR','BF','BI','CM','CV','KY','CF','TD','CL','CO','KM','CG','CD','CR','CI','CU','DJ','DO','DM','EC','EG','SV','GQ','ER','ET','GF','GA','GM','GH','GD','GP','GT','GN','GW','GY','HT','HN','IR','IQ','IL','JM','JO','KE','KW','LB','LS','LR','LY','MG','MW','ML','MQ','MR','MU','MX','MS','MA','MZ','NA','AN','NI','NE','NG','OM','PA','PY','PE','PN','PR','QA','RE','RW','ST','SA','SN','SC','SL','SO','ZA','SH','KN','LC','圣皮埃尔和密克隆岛','VG','SD','SR','SZ','SY','TZ','TG','TT','特里斯坦达库尼亚','TN','特克斯和凯科斯群岛','UG','AE','UY','VE','维尔京群岛（英属）','VI','WF','YE','ZM','ZW','AD','BV','CC','CX','EH','福克兰群岛','法鲁群岛','法属美特罗波利坦','GG','南乔治亚岛和南桑威奇群岛','赫德岛和麦克唐纳岛','加那利群岛','英属印度洋地区(查各群岛)','泽西岛(英属)','南斯拉夫','NF','斯瓦尔巴岛和扬马延岛','南苏丹共和国','法属南部领土','TK','美国本土外小岛屿','伯奈尔岛','库拉索岛(荷兰)','阿森松','圣尤斯塔提马斯岛','北非西班牙属土','亚速尔群岛','马德拉岛','巴利阿里群岛','加罗林群岛','圣马腾岛','尼维斯岛','圣巴特勒米岛','YT','扎伊尔'),
                'E'=>array('RU'),
                'F'=>array('UA')
        );
    
        foreach ($codeArr as $key=>$value) {
            if(in_array($con_iso, $value)){
                return $key;
            }
        }
        
        if($partition == 'SG'){
            return '5';
        }else{
            return '6';
        }
    }

    //美国的邮编分类标示
    function getCodeIdentByUS($code){
        $t = array(
            '0'=>'①(USJFKA)',
            '1'=>'①(USJFKA)',
            '2'=>'①(USJFKA)',
            '3'=>'①(USJFKA)',

            '4'=>'②(US)',
            '5'=>'②(US)',
            '6'=>'②(US)',

            '7'=>'③(USSFOA)',
            '8'=>'③(USSFOA)',
            '9'=>'④(USLAXA)',
            );
        $frist = substr($code, 0, 1 );
        if(!empty($t[$frist])){
            return $t[$frist];
        }
        return '';
    }

    //根据国家返回分区码
    function getPartitionCode($con_iso,$field='partition_code'){
        /*
            partition_code=平常邮件分区号
            g_partition_code=挂号邮件分区号
            p_partition_code=平挂分拣码
        */
        $t = array(
            'RU'=>array('ch_name'=>'俄罗斯','en_name'=>'RUSSIA','partition_code'=>'7','g_partition_code'=>'11','p_partition_code'=>'21'),

            'US'=>array('ch_name'=>'美国','en_name'=>'AMERICA','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'22'),

            'GB'=>array('ch_name'=>'英国','en_name'=>'BRITAIN','partition_code'=>'8','g_partition_code'=>'5','p_partition_code'=>'23'),

            'BR'=>array('ch_name'=>'巴西','en_name'=>'BRAZIL','partition_code'=>'5','g_partition_code'=>'7','p_partition_code'=>'24'),

            'AU'=>array('ch_name'=>'澳大利亚','en_name'=>'AUSTRALIA','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'25'),

            'FR'=>array('ch_name'=>'法国','en_name'=>'FRANCE','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'26'),

            'ES'=>array('ch_name'=>'西班牙','en_name'=>'SPAIN','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'27'),

            'CA'=>array('ch_name'=>'加拿大','en_name'=>'CANADA','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'28'),

            'IL'=>array('ch_name'=>'以色列','en_name'=>'ISRAEL','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'29'),

            'IT'=>array('ch_name'=>'意大利','en_name'=>'ITALY','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'30'),

            'DE'=>array('ch_name'=>'德国','en_name'=>'GERMANY','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'21'),

            'CL'=>array('ch_name'=>'智利','en_name'=>'CHILE','partition_code'=>'6','g_partition_code'=>'8','p_partition_code'=>'32'),

            'SE'=>array('ch_name'=>'瑞典','en_name'=>'SWEDEN','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'33'),

            'BY'=>array('ch_name'=>'白俄罗斯','en_name'=>'BELARUS','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'34'),

            'NO'=>array('ch_name'=>'挪威','en_name'=>'NORWAY','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'35'),

            'NL'=>array('ch_name'=>'荷兰','en_name'=>'NETHERLAND','partition_code'=>'8','g_partition_code'=>'3','p_partition_code'=>'36'),

            'UA'=>array('ch_name'=>'乌克兰','en_name'=>'UKRAINE','partition_code'=>'4','g_partition_code'=>'5','p_partition_code'=>'37'),

            'CH'=>array('ch_name'=>'瑞士','en_name'=>'SWITZERLAND','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'38'),

            'MX'=>array('ch_name'=>'墨西哥','en_name'=>'MEXICO','partition_code'=>'5','g_partition_code'=>'7','p_partition_code'=>'39'),

            'PL'=>array('ch_name'=>'波兰','en_name'=>'POLAND','partition_code'=>'3','g_partition_code'=>'3','p_partition_code'=>'40'),
        );

        if(!empty($t[$con_iso])){
            return $t[$con_iso][$field];
        }
        return '';
    }

    //俄罗斯邮编分类标示
    function getCodeIdentByRU($code){
        $t = array(
            '3'=>'(eka)',
            '4'=>'(eka)',

            '60'=>'(EKA)',
            '61'=>'(EKA)',
            '62'=>'(EKA)',

            '63'=>'(OVB)',
            '64'=>'(OVB)',
            '65'=>'(OVB)',
            '66'=>'(OVB)',
            '67'=>'(OVB)',

            '68'=>'(VVO)',
            '69'=>'(VVO)',

            ''=>'(MOW)'
            );
        $frist1 = substr($code, 0, 1);
        $frist2 = substr($code, 0, 2);

        if(!empty($t[$frist1])){
            return $t[$frist1];
        }
        if(!empty($t[$frist2])){
            return $t[$frist2];
        }
        return 'MOW';
    }

    //wish邮物流数据处理
    function _recreateDataWISH($printInfo,$ordersInfo){
        $this->_ordersInfo = '';
        $wish = new Shipping\Wish();
        $ordersModel=D("Orders");
        $prodModel=M("Product");
        $ordersId = $ordersInfo['orders_id'];
        $requestData=array();
        $isSuccess=false; //验证是否透过
        //地址
        $orders_delivery_name=$ordersInfo['orders_delivery_name'];
        $orders_delivery_address=str_replace(array('>','<'),'',$ordersInfo['orders_delivery_address']);
        $orders_delivery_address2=str_replace(array('>','<'),'',$ordersInfo['orders_delivery_address2']);
        $orders_delivery_city=$ordersInfo['orders_delivery_city'];
        $orders_delivery_state=$ordersInfo['orders_delivery_state'];
        $orders_delivery_postcode=$ordersInfo['orders_delivery_postcode'];
        $orders_delivery_country=$ordersInfo['orders_delivery_country'];    
        $orders_delivery_tel=$ordersInfo['orders_delivery_tel']?$ordersInfo['orders_delivery_tel']:'0-0';
        $orders_delivery_tel=substr(str_replace(array("\n","\t"," "),"",$orders_delivery_tel),0,19);    
        if(empty($orders_delivery_state)){
            $orders_delivery_state="　";
        }   
        //国家过滤
        if($orders_delivery_country=='Netherlands'){
            $orders_delivery_country='Netherland';
        }else if($orders_delivery_country=="Russian Federation"){
            $orders_delivery_country="Russia";
        }
        
        $countryIso=$ordersInfo['orders_delivery_country_iso'];
        if(strtolower(trim($countryIso))=='uk'){
            $countryIso='GB';
        }
        
        //重量
        $pNum=M()->query("select sum(orders_product_quantity) as n from orders_product where orders_id=$ordersId");
        $qty=$pNum[0]['n']?$pNum[0]['n']:(rand(2,9));   
        $weight=$ordersInfo['orders_weight']?round($ordersInfo['orders_weight'],3):0.051;   //单位千克，3位小数
        $weight=round($weight,3);
        if($weight<0.001){
            $weight=0.022;
        }
        //价格
        $price=round($ordersInfo['orders_price_usd'],2);        //申报价值 ,美元 ,2位小数
        if($price>5 || $price<=0){
            $price=round(rand(1,4),2);
        }
        //报关名
        $productId=$ordersInfo['orders_items'][0]['product_id'];
        $prodRes=$prodModel->field('product_dir_id')->where( array("product_id"=>$productId))->find();
        $customsInfo=$wish->getCustomsClassname($prodRes['product_dir_id'],$productId,$ordersInfo['orders_shipping_method']);
        $declarationName=$customsInfo['ClassnameForCustoms'];    //报关名英文    
        $declarationNameCn=$customsInfo['ClassnameForCustomsCn']; //中文
        
        //产品信息
        $productInfo=array(
            'pname'=>$declarationNameCn,
            'pname_en'=>$declarationName,
            'weight'=>$weight,
            'cost'=>$price
        );
        
        //导入时间
        $importTime=$ordersInfo['orders_import_time']?$ordersInfo['orders_import_time']:time();
        //不符合条件的情况
        if(!$orders_delivery_name || !$orders_delivery_address || !$orders_delivery_city || !$orders_delivery_state || !$orders_delivery_postcode || !$orders_delivery_country || !$orders_delivery_tel){
            $errorMsg="生成PDF失败：收件人信息不全，请检查修改!";
        }else if(!$countryIso){
            $errorMsg="生成PDF失败：国家CODE不能为空!";
        }else if(!$ordersInfo['orders_tn']){
            $errorMsg="生成PDF失败：TN不能为空!";
        }else if(!$productInfo){
            $errorMsg="生成PDF失败：产品不能为空!";
        }else{
            $isSuccess=true;
        }
        
        if($isSuccess){ //成功
            //生成数据
            $requestData[$ordersId]=array(
                'sendInfo'=>array(
                    $orders_delivery_name,
                    $orders_delivery_address,
                    $orders_delivery_address2,
                    $orders_delivery_city,
                    $orders_delivery_state,
                    $orders_delivery_postcode,
                    $orders_delivery_tel,
                    $orders_delivery_country
                ),
                'productInfo'=>$productInfo,
                'ordersId'=>$ordersId,
                'importDate'=>date("Ymd",$importTime),
                'ordersDate'=>date("Y-m-d",$importTime),
                'postCode'=>$orders_delivery_postcode,
                'phoneNum'=>$orders_delivery_tel,
                'country_iso'=>$countryIso,
                'productSum'=>$qty,
                'tn'=>$ordersInfo['orders_tn'], 
            );
            $printInfo = array_merge($printInfo,$requestData[$ordersId]);
            return $printInfo;
        }else{ //失败
            $this->saveOrderHistory($ordersId,$errorMsg);
            $ordersModel->where(array(
                "orders_id"=>$ordersId
            ))->save(array(
                'orders_status_children'=>8    
            )); 
            return false;
        }
    }

    //顺丰国际小包平邮
    function _recreateDataSFPY($printInfo,$ordersInfo){
        $kts = new Shipping\Kts();
        $dTmp = array('cell_embeded','cell_in','buttoncell');//含电产品
        $productList = $ordersInfo['orders_items'];
        $ordersShippingExtend = M('orders_shipping_extend');

        $isBat = $kts->checkProductBatterry($productList,$dTmp);//0含电---Y,1不含电---N
        if($isBat === 0){
            $printInfo['isBat'] = 'Y';
        }elseif($isBat === 1){
            $printInfo['isBat'] = 'N';
        }else{
            return false;
        }

        $data = $ordersShippingExtend->where(array('orders_id'=>$ordersInfo['orders_id']))->getField('extend_value');
        $data = json_decode($data,true);
        if(isset($data['direction_code']) && !empty($data['direction_code'])){
            $printInfo['directionCode'] = $data['direction_code'];
            $printInfo['mailno'] = $printInfo['tn']?$printInfo['tn']:$data['mailno'];
            return $printInfo;
        }else{
            return false;
        }
    }

    //老挝平邮纯电池
    function _recreateDataLWGH_TN($printInfo,$ordersInfo){
        $kts = new Shipping\Kts();
        $dTmp = array('cell_embeded','cell_in','buttoncell','special01');//含电产品
        $productList = $ordersInfo['orders_items'];

        $isBat = $kts->checkProductBatterry($productList,$dTmp);//0含电---D,1不含电---P
        if($isBat === 0){
            $printInfo['isBat'] = 'D';
        }elseif($isBat === 1){
            $printInfo['isBat'] = '';
        }else{
            return false;
        }
        return $printInfo;
    }

     //顺丰国际小包平邮
    function _recreateDataSF_TN($printInfo,$ordersInfo){
        $kts = new Shipping\Kts();
        $dTmp = array('cell_embeded','cell_in','buttoncell');//含电产品
        $productList = $ordersInfo['orders_items'];
        $ordersShippingExtend = M('orders_shipping_extend');

        $isBat = $kts->checkProductBatterry($productList,$dTmp);//0含电---Y,1不含电---N
        if($isBat === 0){
            $printInfo['isBat'] = 'Y';
        }elseif($isBat === 1){
            $printInfo['isBat'] = 'N';
        }else{
            return false;
        }
        $data = $ordersShippingExtend->where(array('orders_id'=>$ordersInfo['orders_id']))->getField('extend_value');
        $data = json_decode($data,true);
        if(isset($data['direction_code']) && !empty($data['direction_code']) && isset($data['agent_mailno']) && !empty($data['agent_mailno'])){
            $printInfo['directionCode'] = $data['direction_code'];
            $printInfo['agentTn'] = $data['agent_mailno'];
            $printInfo['mailno'] = $printInfo['tn']?$printInfo['tn']:$data['mailno'];;
            return $printInfo;
        }else{
            return false;
        }
    }

    //yym海外仓
    function _recreateDataYYM($printInfo,$ordersInfo){
        $postCode = trim($ordersInfo['orders_delivery_postcode']);
        $printInfo['areaCode'] = $this->_areaCodeYYM($postCode);
        if(!$printInfo['areaCode']){
            return false;
        }
        $skusArr = array();
        foreach ($ordersInfo['orders_items'] as $key => $value) {
            $skusArr[] = $value['orders_item_org_sku'];
        }
        $printInfo['skus'] = implode(";", $skusArr);
        return $printInfo;
    }

    function _areaCodeYYM($postCode){
        $code = $postCode[0].$postCode[1];
        $arrayNY = array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26');
        $arrayCA = array('90','91','92','93','94','95','96','97','98','99','81','82','83','84','85','86','88','89','59');
        $arrayTX = array('70','71','72','73','74','75','76','77','78','79','66','67','39','80','87');
        $arrayFL = array('30','31','32','33','34','35','36','37','38','27','28','29');
        $arrayCH = array('40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','60','61','62','63','64','65','68','69');
        if(in_array($code, $arrayNY)){
            $areaCode = '1 NY';
        }elseif(in_array($code, $arrayCA)){
            $areaCode = '2 CA';
        }elseif(in_array($code, $arrayTX)){
            $areaCode = '3 TX';
        }elseif(in_array($code, $arrayFL)){
            $areaCode = '4 FL';
        }elseif(in_array($code, $arrayCH)){
            $areaCode = '5 CH';
        }else{
            return false;
        }
        return $areaCode;
    }
}